package cn.regexp.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.regexp.domain.ShopCollect;
import cn.regexp.domain.ShopGoods;
import cn.regexp.mapper.CollectMapper;
import cn.regexp.service.ICollectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CollectServiceImpl extends ServiceImpl<CollectMapper, ShopCollect> implements ICollectService {
    @Autowired
    private CollectMapper collectMapper;
    @Autowired
    private GoodsServiceImpl goodsService;
    @Override
    public boolean collect(Long goodsId, Long userId) {
        ShopCollect collect = new ShopCollect();
        collect.setGoodsId(goodsId);
        collect.setUserId(userId);
        collect.setCollectTime(new Date());
        collect.setIsDel(ShopCollect.DELETE_NO);
        ShopGoods goods = goodsService.getById(goodsId);
        collect.setCoverUrl(goods.getCoverUrl());
        collect.setGoodsName(goods.getGoodsName());
        collect.setGoodsPrice(goods.getGoodsPrice());
        goods.setGoodsNum(goods.getCollectNum() + 1);
        goodsService.updateById(goods);
        return collectMapper.insert(collect) > 0;
    }

    @Override
    public boolean cancelCollect(Long goodsId, Long userId) {
        UpdateWrapper<ShopCollect> wrapper = new UpdateWrapper<>();
        wrapper.eq("goods_id", goodsId)
                .eq("user_id", userId);
        ShopCollect collect = new ShopCollect();
        collect.setIsDel(ShopCollect.DELETE_YES);
        ShopGoods goods = goodsService.getById(goodsId);
        goods.setGoodsNum(goods.getCollectNum() - 1);
        goodsService.updateById(goods);
        return super.update(collect, wrapper);
    }

    @Override
    public boolean isCollect(Long goodsId, Long userId) {
        QueryWrapper<ShopCollect> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", goodsId)
                .eq("user_id", userId)
                .eq("is_del", ShopCollect.DELETE_NO);
        ShopCollect collect = super.getOne(wrapper);
        return ObjectUtil.isNotEmpty(collect);
    }

    @Override
    public List<ShopCollect> queryCollectGoodsByUserId(Long userId) {
        QueryWrapper<ShopCollect> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("is_del", ShopCollect.DELETE_NO);
        List<ShopCollect> collectList = super.list(wrapper);
        collectList.forEach(item -> {
            ShopGoods shopGoods = goodsService.getById(item.getGoodsId());
            BeanUtils.copyProperties(shopGoods, item);
        });
        return collectList;
    }
}
